package net.dreamlu.assets;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.IPlugin;

import net.dreamlu.assets.utils.IOUtils;
import net.dreamlu.assets.utils.ResourceUtils;

/**
 * jfinal-assets插件
 * 
 * 启动前完成压缩工作，提高性能，稳定性。达到商用级别~ 
 * 
 * @author L.cm
 * email: 596392912@qq.com
 * site:http://www.dreamlu.net
 * @date 2017年3月22日下午8:23:56
 */
public class AssetsPlugin implements IPlugin {
	private static ConcurrentMap<String, String> ASSETS_MAP = new ConcurrentHashMap<String, String>();
	private static final String DEFAULT_ASSETS_DIR = "assets";
	private static final String DEFAULT_COMBO_OUT_DIR = "assets";
	private static final Charset UTF_8 = Charset.forName("utf-8");
	private final AssetsCompressor assetsCompressor;
	/**
	 * jjs,jcss目录
	 */
	private String assetsDir;
	private String[] assetsFiles;
	/**
	 * 合并压缩后的输出目录
	 */
	private String comboOutDir;
	
	public AssetsPlugin() {
		this.assetsDir = DEFAULT_ASSETS_DIR;
		this.comboOutDir = DEFAULT_COMBO_OUT_DIR;
		this.assetsCompressor = new AssetsCompressor(); 
	}

	public AssetsPlugin setAssetsDir(String assetsDir) {
		this.assetsDir = assetsDir;
		return this;
	}

	public void setAssetsFiles(String... assetsFiles) {
		this.assetsFiles = assetsFiles;
	}

	public AssetsPlugin setComboOutDir(String comboOutDir) {
		this.comboOutDir = comboOutDir;
		return this;
	}

	@Override
	public boolean start() {
		if (!StrKit.notBlank(assetsFiles)) {
			throw new RuntimeException("assetsFiles path can't Blank!");
		}
		List<String> assetsList = new ArrayList<String>();
		for (String file : assetsFiles) {
			boolean isCss = true;
			if (file.endsWith(".jjs")) {
				isCss = false;
			}
			String assetsPath = assetsDir + file;
			InputStream in = null;
			BufferedReader reader = null;
			try {
				in = ResourceUtils.getResource(assetsPath);
				InputStreamReader isReader = new InputStreamReader(in, UTF_8);
				reader = new BufferedReader(isReader);
				String line = reader.readLine();
			} catch (IOException e) {
				throw new RuntimeException(e);
			} finally {
				IOUtils.closeQuietly(reader);
				IOUtils.closeQuietly(in);
			}
			// MD5 得到新文件名
//			FileOutputStream output = new FileOutputStream(newPath);
//			Writer out = new OutputStreamWriter(output, UTF_8);
		}
		
		return false;
	}

	@Override
	public boolean stop() {
		return false;
	}

}
